package service

import (
	"anban/models"
	"anban/utils"
	"github.com/astaxie/beego/orm"
	"net/url"
)

// 获取问题反馈信息
func GetFeedbackInfo(p map[string]interface{}) *models.Feedback {
	o := orm.NewOrm()
	feedback := &models.Feedback{}
	qs := o.QueryTable("Feedback")
	if _, ok := p["relation"]; ok && p["relation"].(bool) {
		qs = qs.RelatedSel()
	}
	if _, ok := p["id"]; ok {
		qs = qs.Filter("id", p["id"])
	}
	qs.One(feedback)
	if _, ok := p["convert"]; ok && p["convert"].(bool) {
		if feedback.Id > 0 {
			feedback.CreatedShow = feedback.Created.Format("2006-01-02 15:04:05")
		}
	}
	return feedback
}

// 添加问题反馈信息
func AddFeedback(input url.Values) (int64, error) {
	o := orm.NewOrm()
	feedback := &models.Feedback{}
	user := &models.User{}
	if _, ok := input["user_id"]; ok {
		user.Id = utils.Atoi64(input["user_id"][0])
		o.Read(user)
	}
	feedback.User = user
	if _, ok := input["content"]; ok {
		feedback.Content = input["content"][0]
	}
	return o.Insert(feedback)
}

// 修改问题反馈信息
func EditFeedback(input url.Values) (int64, error) {
	o := orm.NewOrm()
	p := orm.Params{}
	for k, v := range input {
		if k == "id" || k == "_xsrf" {
			continue
		}
		p[k] = v[0]
	}
	return o.QueryTable("Feedback").Filter("id", input["id"][0]).Update(p)
}

// 获取问题反馈列表
func GetFeedbackList(p map[string]interface{}) (int64, []*models.Feedback) {
	var feedbackList []*models.Feedback
	o := orm.NewOrm()
	qs := o.QueryTable("Feedback")
	if _, ok := p["userId"]; ok {
		qs = qs.Filter("user_id", p["userId"])
	}
	if _, ok := p["realName"]; ok {
		qs = qs.Filter("User__RealName", p["realName"])
	}
	if _, ok := p["phone"]; ok {
		qs = qs.Filter("User__Phone", p["phone"])
	}
	totalCount, _ := qs.Count()
	curPage, ok := p["curPage"]
	perCount, _ := p["perCount"]
	if ok {
		start := perCount.(int) * (curPage.(int) - 1)
		qs = qs.Limit(perCount, start)
	}
	qs.All(&feedbackList)
	if _, ok := p["convert"]; ok && p["convert"].(bool) {
		for _, feedback := range feedbackList {
			feedback.CreatedShow = feedback.Created.Format("2006-01-02 15:04:05")
		}
	}
	return totalCount, feedbackList
}